<template>
  <div>
    <div class="main">
      <div class="report-list-notice-bar">
        <van-notice-bar left-icon="volume-o" :text="noticeText" />
      </div>

      <template v-if="isShowList(routerField)">
        <CommonFold
          class="report-items"
          v-for="(item, index) in routerField"
          :key="index"
        >
          <template #header="{ show }">
            <div class="header__title title-bg-1" v-if="isShow(item)">
              <div>{{ item.name }}</div>
              <div class="arrow__pic__wrap">
                <img
                  class="arrow__pic__img"
                  :src="
                    show
                      ? require('@/assets/down.svg')
                      : require('@/assets/up.svg')
                  "
                  alt=""
                />
              </div>
            </div>
          </template>
          <template #body>
            <div
              class="body__content"
              v-for="(child, index) in item.children"
              :key="index"
            >
              <div
                class="report-unit"
                @click="openDetail(child)"
                v-if="child.show"
              >
                <div class="report-unit__icon">
                  <img
                    class="report-card__pic__img"
                    :src="require('@/assets/report.svg')"
                    alt=""
                  />
                </div>
                <div class="report-unit__title">{{ child.name }}</div>
                <div class="report-unit__h5__sign" v-if="child.isH5">H5</div>
              </div>
            </div>
          </template>
        </CommonFold>
      </template>
      <template v-else>
        <div class="report-card__no__data">
          <img :src="require('@/assets/no-data.svg')" alt="" />
        </div>
      </template>
    </div>

    <CommonFloatMenu :columns="menuColumns"></CommonFloatMenu>

    <van-popup v-model:show="showPositionsPicker" position="bottom">
      <van-picker
        title="切换职位"
        :columns="positionColumns"
        :default-index="defaultPositionIndex"
        @confirm="onPositionConfirm"
        @cancel="showPositionsPicker = false"
      />
    </van-popup>

    <!-- <div v-if="loginShow" class="to-login" @click="toLogin">登录</div> -->
  </div>
</template>

<script>
import CommonFloatMenu from "@/components/common-float-menu/index.vue";
import CommonFold from "@/components/common-fold/index.vue";
import axios from "axios";
import { prexUrl } from "util/index.js";
import {
  Toast,
  Picker as VanPicker,
  Popup as VanPopup,
  NoticeBar as VanNoticeBar,
} from "vant";
import { mapState } from "vuex";
import { routerField } from "./routerField";

export default {
  name: "rpt-ls",
  components: {
    CommonFloatMenu,
    CommonFold,
    VanPicker,
    VanPopup,
    VanNoticeBar,
  },
  data() {
    return {
      routerField: routerField,
      menuConfig: {},
      menuColumns: [
        {
          title: "职位",
          colProps: {
            background: " #2751a6",
          },
          onClick: () => {
            this.showPositionsPicker = true;
          },
        },
      ],
      loginShow: process.env.NODE_ENV === "dev",
      reportList: [
        {
          id: 18,
          title: "时效报表",
          link: "spc-rt/ageingReport",
        },
      ],
      positionColumns: [],
      showPositionsPicker: false,
    };
  },
  computed: {
    ...mapState({
      menus: (state) => state.userInfo.menus,
      noticeText: (state) => {
        let userName = state.userInfo?.user?.userName;
        let positionName = state.userInfo?.corpPosition?.position?.positionName;
        return `用户：${userName}，职位：${positionName}。用户：${userName}，职位：${positionName}。用户：${userName}，职位：${positionName}。`;
      },
      defaultPositionIndex(state) {
        let positionUid = state.userInfo?.corpPosition?.position?.uid;
        let index =
          this.positionColumns.findIndex((item) => {
            if (item.value == positionUid) {
              return true;
            }
          }) || 0;
        return index;
      },
    }),
  },
  watch: {
    menus(newVal, oldVal) {
      this.getMenuShow();
    },
  },
  methods: {
    isShowList(routerField) {
      let list = [];
      routerField.forEach((element) => {
        element.children.forEach((item) => {
          if (item.show) {
            list.push(item.name);
          }
        });
      });
      return list.length > 0;
    },
    isShow(child) {
      let flag = child.children.some((item) => {
        return item && item.show;
      });
      return flag;
    },
    getUserInfoAndPositions() {
      let token = this.$route.query.token;
      return new Promise((resolve, reject) => {
        this.$store.dispatch("getUserInfoByToken", token).then((res) => {
          console.log("userId", res.user.uid);
          this.$store
            .dispatch("getPositionsByUserId", {
              userId: res.user.uid,
              accessToken: token,
            })
            .then((positions) => {
              resolve(positions);
              this.positionColumns = positions.map((item) => {
                return {
                  text: item.position.positionName,
                  value: item.position.uid,
                  ...item,
                };
              });
              console.log("positions", positions);
            });
        });
      });
    },
    getH5Show() {
      let _this = this;

      this.routerField = this.routerField.map((item) => {
        item.children = item.children.map((val) => {
          if (val.isH5) {
            val.show = true;
          }
          return val;
        });

        return item;
      });

      axios({
        method: "post",
        headers: {
          Authorization: "Bearer " + _this.$route.query.token,
        },
        params: {
          page: 1,
          size: 1000,
        },
        data: {
          positionId: _this.$store.state.userInfo?.corpPosition?.position?.uid,
        },
        url: "/scm/api/v1/scmPositionAuthority/list",
      }).then((response) => {
        console.log("response", response.data.data);
      });
    },
    getMenuShow() {
      let accessMenus = this.menus;
      // 该角色的菜单  和本地菜单对比过滤......
      if (!accessMenus) {
        return false;
      }
      let reportNameAssemble = [];
      accessMenus = accessMenus.find((item) => {
        return item.name === "报表";
      });
      if (
        accessMenus &&
        accessMenus.children &&
        accessMenus.children.length > 0
      ) {
        reportNameAssemble = accessMenus.children.map((item) => {
          return item.name;
        });
      }
      this.routerField = routerField.map((item) => {
        item.children.map((val) => {
          if (reportNameAssemble.includes(val.name)) {
            val.show = true;
          } else {
            val.show = false;
          }
        });
        return item;
      });
    },
    openDetail(child) {
      let { route: link, isH5 } = child;
      let token = this.$route.query.token;

      if (!link) {
        return false;
      }
      if (!token) {
        this.$router.push({
          path: "/login",
        });
        // window.location.href = prexUrl() + "/longnows#/login";
      } else {
        if (isH5) {
          this.$router.push({
            path: "/" + link,
            query: {
              token: token,
            },
          });
        } else {
          window.location.href = prexUrl() + "/" + link + "?token=" + token;
        }
        // window.location.href =
        //   prexUrl() + "/longnows#/" + link + "?token=" + token;
      }
    },
    async onPositionConfirm(position) {
      let _this = this;
      let token = this.$route.query.token;
      this.$store
        .dispatch("changePosition", {
          positionId: position.value,
          accessToken: token,
        })
        .then(async (res) => {
          await _this.getMenuShow();
          await _this.getH5Show();

          _this.$router.push({
            query: {
              token: _this.$store.state.userInfo.accessToken,
            },
          });
          console.log("res", res);
        });

      this.showPositionsPicker = false;
    },
  },
  async mounted() {
    await this.getUserInfoAndPositions();
    await this.getH5Show();
    await this.getMenuShow();
    await this.getH5Show();
  },
  beforeRouteLeave(to, from, next) {
    if (to.path == "/about") {
      this.$store.commit("SetKeep", this.$route.name);
    } else if (to.path == "/login") {
      this.$store.commit("RemoveKeep", this.$route.name);
    }
    next();
    // console.log(to, from, next);
  },
  // beforeRouteEnter(to, from, next){
  //   console.log(to, from, next)
  //   next()
  // }
};
</script>

<style scoped lang="less">
.main {
  padding: 40px 0px;
}
.report-items {
  margin-bottom: 20px;
}

.report-unit {
  width: calc(100% - 20px);
  height: 45px;
  line-height: 45px;
  display: flex;
  align-content: center;
  padding: 0 12px;
  box-shadow: 0 1px 8px 0 #ebedf0;
  border-radius: 20px;
  margin-top: 15px;
}

.report-unit__icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin-right: 20px;
  padding: 3px 20px;
}

.report-card__pic__img {
  width: 20px;
}

.report-card__no__data {
  text-align: center;
  padding-top: 30%;
  img {
    width: 70%;
  }
}

.report-unit__title {
  font-family: PingFang SC;
  font-size: 15px;
  font-weight: 400;
  line-height: 45px;
  letter-spacing: 0em;
  text-align: left;
}
.report-unit__h5__sign {
  margin-left: auto;
  margin-right: 10px;
  font-weight: 600;
}

/*  */
.header__title {
  width: calc(100% - 20px);
  margin: 0px 10px;
  box-sizing: border-box;
  height: 45px;
  line-height: 45px;
  font-family: PingFang SC;
  font-size: 15px;
  font-weight: 400;
  border-radius: 20px;
  padding: 0 25px;
  display: flex;
  justify-content: space-between;
  align-content: center;
  background: rgba(51, 84, 244, 1);
  color: white;
  font-size: 16px;
}

.body__content {
  width: calc(100% - 20px);
  margin: 0px 10px;
  box-sizing: border-box;
}

.arrow__pic__wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.arrow__pic__img {
  width: 25px;
}

.title-bg-1 {
  background: rgba(51, 84, 244, 1);
}
.title-bg-2 {
  background: rgba(51, 151, 244, 1);
}
.title-bg-3 {
  background: rgba(51, 186, 244, 1);
}
.report-list-notice-bar {
  position: fixed;
  top: 0;
  width: 100%;
}
</style>
